package xiaohao.order.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Item;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItemsListGetResponse;

import xiaohao.order.dao.ItemDao;
import xiaohao.order.top.TopDaoSupport;

public class DefaultItemDao extends TopDaoSupport implements ItemDao {

	@Override
	public String getCatById(long id) {
		ItemGetRequest request = new ItemGetRequest();
		request.setFields("cid");
		request.setNumIid(id);
		ItemGetResponse response;
		try {
			response = getTaobaoClient().execute(request);
		} catch (ApiException e) {
			log.info(e);
			return null;
		}
		if (!response.isSuccess()) {
			return null;
		}
		
		long cid = response.getItem().getCid();
		
		ItemcatsGetRequest request2 = new ItemcatsGetRequest();
		request2.setFields("name");
		request2.setCids(cid + "");
		ItemcatsGetResponse response2;
		try {
			response2 = getTaobaoClient().execute(request2);
		} catch (ApiException e) {
			log.info(e);
			return null;
		}
		if (!response2.isSuccess()) {
			return null;
		}
		return response2.getItemCats().get(0).getName();
	}

	@Override
	public List<Long> getCidsByIds(List<Long> ids) {
		ItemsListGetRequest request = new ItemsListGetRequest();
		request.setFields("cid");
		request.setNumIids(StringUtils.join(ids, ","));
		ItemsListGetResponse response;
		try {
			response = getTaobaoClient().execute(request);
		} catch (ApiException e) {
			log.info(e);
			return Lists.newArrayList();
		}
		
		if (!response.isSuccess()) {
			return null;
		}
		
		return Lists.transform(response.getItems(), new Function<Item, Long>() {

			@Override
			public Long apply(Item input) {
				return input.getCid();
			}
		});
	}

}
